<template>
  <view class="xen-audit-timeline">
    <view class="timeline-header">
      <text class="timeline-title">审核流程</text>
    </view>

    <view class="timeline-container">
      <!-- 空状态显示 -->
      <view v-if="timelineSteps.length === 0" class="timeline-empty">
        <text class="empty-text">暂无审核流程</text>
        <text class="empty-desc">该单据还没有审核流程记录</text>
      </view>

      <!-- 时间线内容 -->
      <view
        v-for="(step, index) in timelineSteps"
        :key="step.ID || index"
        class="timeline-item"
        :class="getStepClass(step.ApproveResult)"
      >
        <!-- 时间线节点 -->
        <view class="timeline-node">
          <!-- 审核人头像 -->
          <view class="timeline-avatar">
            <image
              v-if="step.ApproverAvatar"
              :src="getImageUrl(step.ApproverAvatar)"
              class="avatar-img"
              mode="aspectFill"
              @error="handleAvatarError"
            />
            <uni-icons
              v-else
              type="person-filled"
              size="16"
              color="#ffffff"
            ></uni-icons>
          </view>

          <!-- 连接线 -->
          <view
            v-if="index < timelineSteps.length - 1"
            class="timeline-line"
            :class="
              getLineClass(
                step.ApproveResult,
                timelineSteps[index + 1]?.ApproveResult,
              )
            "
          ></view>
        </view>

        <!-- 步骤内容 -->
        <view class="timeline-content">
          <view class="step-header">
            <view class="step-title-section">
              <text class="step-title">{{
                step.ApproverName || step.Approver || "系统"
              }}</text>
              <text class="step-workflow" v-if="step.ApproveGroup">{{
                step.ApproveGroup
              }}</text>
            </view>
            <view
              class="step-status"
              :class="getStatusBadgeClass(step.ApproveResult)"
            >
              <text class="status-text">{{
                getStatusText(step.ApproveResult)
              }}</text>
            </view>
          </view>

          <view v-if="step.ApproveTime" class="step-time">
            <uni-icons type="calendar" size="14" color="#666"></uni-icons>
            <text class="time-text">{{ formatTime(step.ApproveTime) }}</text>
          </view>

          <!-- 审批评论 -->
          <view v-if="step.ApproveComment" class="step-comment">
            <uni-icons type="chat" size="14" color="#666"></uni-icons>
            <text class="comment-text">{{ step.ApproveComment }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { formatDateTime } from "@/utils/xenUtils";

// 导入 WorkflowInfo 接口
interface WorkflowInfo {
  ActivityId: string;
  ApproveGroup: string;
  ApproveResult: string;
  ApproveTime: string;
  Approver: string;
  ApproverName: string;
  ApproverAvatar: string;
  ApproveComment?: string; // 审批评论，用于显示拒绝理由或同意理由
  ID: string;
  ModelId: string;
  ModelType: string;
  Step: number;
  WorkflowId: string;
  WorkflowName: string;
}

// 组件属性
interface Props {
  steps?: WorkflowInfo[];
}

const props = withDefaults(defineProps<Props>(), {
  steps: () => [],
});

// 计算实际使用的步骤数据
const timelineSteps = computed(() => {
  return props.steps || [];
});

// 获取图片URL - 参考 work.vue 的实现方式
const getImageUrl = (fileId: string): string => {
  if (!fileId) return "";
  return `${
    import.meta.env.VITE_BASE_URL
  }/api/_file/getfile/${fileId}?t=${Date.now()}`;
};

// 处理头像加载错误
const handleAvatarError = () => {
  // 头像加载失败时的处理逻辑，这里可以设置默认头像或者其他处理
  console.log("头像加载失败");
};

// 格式化时间显示
const formatTime = (timeStr: string): string => {
  if (!timeStr) return "";
  try {
    const formattedTime = formatDateTime(timeStr);
    if (formattedTime) {
      return formattedTime;
    }

    // 如果 formatDateTime 返回空字符串，说明日期解析失败
    // 尝试直接使用 Date 构造函数并手动格式化
    const date = new Date(timeStr);
    if (!isNaN(date.getTime())) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    }

    // 如果所有格式化都失败，返回原始字符串
    console.warn("日期格式化失败:", timeStr);
    return timeStr;
  } catch (error) {
    console.error("日期格式化错误:", error, "原始时间:", timeStr);
    return timeStr;
  }
};

// 获取步骤样式类 - 直接基于 ApproveResult
const getStepClass = (approveResult: string): string => {
  const normalizedResult = approveResult?.toLowerCase() || "";
  if (normalizedResult.includes("通过") || normalizedResult === "approved") {
    return "timeline-item--completed";
  }
  if (normalizedResult.includes("拒绝") || normalizedResult === "rejected") {
    return "timeline-item--rejected";
  }
  if (
    normalizedResult.includes("处理中") ||
    normalizedResult.includes("审核中") ||
    normalizedResult === "processing"
  ) {
    return "timeline-item--processing";
  }
  return "timeline-item--pending";
};

// 获取连接线样式类
const getLineClass = (currentResult: string, nextResult?: string): string => {
  const normalizedCurrent = currentResult?.toLowerCase() || "";
  if (normalizedCurrent.includes("通过") || normalizedCurrent === "approved") {
    return "timeline-line--completed";
  }
  if (
    normalizedCurrent.includes("处理中") ||
    normalizedCurrent.includes("审核中") ||
    normalizedCurrent === "processing"
  ) {
    return "timeline-line--processing";
  }
  return "timeline-line--pending";
};

// 获取状态徽章样式类
const getStatusBadgeClass = (approveResult: string): string => {
  const normalizedResult = approveResult?.toLowerCase() || "";
  if (normalizedResult.includes("通过") || normalizedResult === "approved") {
    return "step-status--completed";
  }
  if (normalizedResult.includes("拒绝") || normalizedResult === "rejected") {
    return "step-status--rejected";
  }
  if (
    normalizedResult.includes("处理中") ||
    normalizedResult.includes("审核中") ||
    normalizedResult === "processing"
  ) {
    return "step-status--processing";
  }
  return "step-status--pending";
};

// 获取状态文本
const getStatusText = (approveResult: string): string => {
  if (!approveResult) return "待处理";

  const normalizedResult = approveResult.toLowerCase();
  if (normalizedResult.includes("通过") || normalizedResult === "approved") {
    return "已通过";
  }
  if (normalizedResult.includes("拒绝") || normalizedResult === "rejected") {
    return "已拒绝";
  }
  if (
    normalizedResult.includes("处理中") ||
    normalizedResult.includes("审核中") ||
    normalizedResult === "processing"
  ) {
    return "处理中";
  }

  // 直接返回原始结果，如果不匹配预定义的状态
  return approveResult || "待处理";
};
</script>

<style lang="scss" scoped>
.xen-audit-timeline {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  margin: 10px 0;
  overflow: hidden;
}

.timeline-header {
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;

  .timeline-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    position: relative;
    padding-left: 12px;
    margin: 0;

    &::before {
      content: "";
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background: linear-gradient(135deg, #7579f5 0%, #9973f8 100%);
      border-radius: 2px;
    }
  }
}

.timeline-container {
  padding: 24px;
}

// 空状态样式
.timeline-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  text-align: center;

  .empty-text {
    font-size: 16px;
    color: #666;
    font-weight: 500;
    margin-bottom: 8px;
  }

  .empty-desc {
    font-size: 14px;
    color: #999;
    line-height: 1.4;
  }
}

.timeline-item {
  display: flex;
  position: relative;

  &:last-child {
    .timeline-line {
      display: none;
    }
  }
}

.timeline-node {
  position: relative;
  margin-right: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

// 头像样式
.timeline-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 2;
  background: #409eff;
  border: 2px solid #ffffff;
  overflow: hidden;

  .avatar-img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
  }
}

.timeline-line {
  width: 2px;
  height: 40px;
  margin-top: 5px;

  &--pending {
    background-color: #d9d9d9;
  }

  &--processing {
    background: linear-gradient(to bottom, #7881de 0%, #d9d9d9 100%);
  }

  &--completed {
    background-color: #52c41a;
  }
}

.timeline-content {
  flex: 1;
  padding-bottom: 10px;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 5px;
}

.step-title-section {
  flex: 1;

  .step-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    display: block;
    margin-bottom: 4px;
  }

  .step-workflow {
    font-size: 12px;
    color: #666;
    display: block;
  }
}

.step-status {
  padding: 2px 7px;
  border-radius: 16px;
  flex-shrink: 0;
  display: flex;

  .status-text {
    font-size: 10px;
    font-weight: 500;
  }

  &--pending {
    background-color: #f3f4f6;

    .status-text {
      color: #6b7280;
    }
  }

  &--processing {
    background-color: #e0e7ff;

    .status-text {
      color: #4338ca;
    }
  }

  &--completed {
    background-color: #d1fae5;

    .status-text {
      color: #059669;
    }
  }

  &--rejected {
    background-color: #fee2e2;

    .status-text {
      color: #dc2626;
    }
  }
}

.step-info {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;

  .step-operator {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }
}

.step-time {
  display: flex;
  align-items: center;
  gap: 6px;

  .time-text {
    font-size: 12px;
    color: #666;
  }
}

.step-comment {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 2px;
  padding: 0px 5px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 2px solid #e9ecef;

  .comment-text {
    font-size: 10px;
    color: #495057;
    line-height: 1.4;
    flex: 1;
    word-break: break-word;
  }
}
</style>
